<?php

namespace addons\csminvite;

use addons\csminvite\library\CsmUtils;
use addons\csminvite\library\CsminviteNotify;
use think\Addons;
use think\Request;
use think\Session;
use addons\csminvite\library\CsminviteNotifyType;
use addons\csminvite\library\CsminviteQd;
use addons\csminvite\library\CsminviteInvcode;
use app\common\library\Menu;

/**
 * 插件
 */
class Csminvite extends Addons
{

    /**
     * 插件安装方法
     *
     * @return bool
     */
    public function install()
    {
        $menu = [
            [
                'name'    => 'csminvite',
                'title'   => '会员注册邀请',
                'sublist' => [
                    [
                        'name'    => 'csminvite/dashboard',
                        'title'   => '推广情况报表',
                        'icon'    => 'fa fa-meetup',
                        'sublist' => [
                            [
                                'name'  => 'csminvite/dashboard/index',
                                'title' => '查看报表页面'
                            ],
                            [
                                'name'  => 'csminvite/dashboard/indexChartDataset',
                                'title' => '查看报表数据'
                            ]
                        ]
                    ],
                    [
                        'name'    => 'csminvite/notify',
                        'title'   => '通过邮件邀请推广',
                        'icon'    => 'fa fa-meetup',
                        'sublist' => [
                            [
                                'name'  => 'csminvite/notify/index',
                                'title' => '查看'
                            ],
                            [
                                'name'  => 'csminvite/notify/add',
                                'title' => '添加'
                            ],
                            [
                                'name'  => 'csminvite/notify/edit',
                                'title' => '修改'
                            ],
                            [
                                'name'  => 'csminvite/notify/del',
                                'title' => '删除'
                            ],
                            [
                                'name'  => 'csminvite/notify/notifyUserajax',
                                'title' => '发送邀请邮件'
                            ],
                            [
                                'name'  => 'csminvite/notifyuser/index',
                                'title' => '邀请人列表'
                            ],
                            [
                                'name'  => 'csminvite/notifyuser/add',
                                'title' => '邀请人添加'
                            ],
                            [
                                'name'  => 'csminvite/notifyuser/edit',
                                'title' => '邀请人修改'
                            ],
                            [
                                'name'  => 'csminvite/notifyuser/del',
                                'title' => '邀请人删除'
                            ],
                        ]
                    ],
                    [
                        'name'    => 'csminvite/qd',
                        'title'   => '通过二维码推广邀请',
                        'icon'    => 'fa fa-file-text-o',
                        'sublist' => [
                            [
                                'name'  => 'csminvite/qd/index',
                                'title' => '查看'
                            ],
                            [
                                'name'  => 'csminvite/qd/add',
                                'title' => '添加'
                            ],
                            [
                                'name'  => 'csminvite/qd/edit',
                                'title' => '修改'
                            ],
                            [
                                'name'  => 'csminvite/qd/del',
                                'title' => '删除'
                            ],
                            [
                                'name'  => 'csminvite/qd/generateqdPng',
                                'title' => '生成二维码'
                            ],
                            [
                                'name'  => 'csminvite/qd/generateqdimg',
                                'title' => '二维码页'
                            ],
                            [
                                'name'  => 'csminvite/qduser/index',
                                'title' => '注册账号列表'
                            ],
                        ]
                    ],
                    [
                        'name'    => 'csminvite/invcode',
                        'title'   => '邀请码注册推广',
                        'icon'    => 'fa fa-file-text-o',
                        'sublist' => [
                            [
                                'name'  => 'csminvite/invcode/index',
                                'title' => '查看'
                            ],
                            [
                                'name'  => 'csminvite/invcode/add',
                                'title' => '添加'
                            ],
                            [
                                'name'  => 'csminvite/invcode/edit',
                                'title' => '修改'
                            ],
                            [
                                'name'  => 'csminvite/invcode/del',
                                'title' => '删除'
                            ],
                            [
                                'name'  => 'csminvite/invcode/addinvcode',
                                'title' => '生成验证码'
                            ],
                            [
                                'name'  => 'csminvite/invcodeuser/index',
                                'title' => '邀请函列表'
                            ],
                        ]
                    ]
                ]
            ]
        ];
        Menu::create($menu);
        return true;
    }

    /**
     * 插件卸载方法
     *
     * @return bool
     */
    public function uninstall()
    {
        Menu::delete("csminvite");
        return true;
    }

    /**
     * 插件启用方法
     *
     * @return bool
     */
    public function enable()
    {
        Menu::enable("csminvite");
        return true;
    }

    /**
     * 插件禁用方法
     *
     * @return bool
     */
    public function disable()
    {
        Menu::disable("csminvite");
        return true;
    }

    /**
     * 会员注册前，校验csminviate逻辑
     * Nofify:
     * http://127.0.0.1/fastadmin_plugin_csmmeet/public/index/user/register.html?csminvite=notify_abc_1&csminvitesign=md5
     */
    public function actionBegin()
    {
        trace("csminvite actionBegin begin");
        $request = Request::instance();
        if ($request->path() == "index/user/register" && $request->isGet()) {
            return $this->_registerget($request);
        } else {
            if ($request->path() == "index/user/register" && $request->isPost()) {
                return $this->_registerpost($request);
            }
        }
    }

    /**
     * 注册成功
     */
    public function userRegisterSuccessed($dbuser, $data)
    {
        trace("csminvite userRegisterSuccessed begin");
        $csminvite = Session::get('csminvite');
        if (CsmUtils::isNullOrBlank($csminvite)) {
            return;
        }
        list($invtype, $invkey, $invid) = $this->_parseCsminvitekey($csminvite);
        switch ($invtype) {
            case 'notify':
                $invite = new CsminviteNotify();
                $invite->afterRegistered($dbuser, $invkey, $invid);
                break;
            case 'qd':
                $invite = new CsminviteQd();
                $invite->afterRegistered($dbuser, $invkey, $invid);
                break;
            case 'invcode':
                $invite = new CsminviteInvcode();
                $invite->afterRegistered($dbuser, $invkey, $invid);
                break;
            default:
                $this->_error("参数错误：csminvite#1");
        }
    }

    /**
     * 注册提交，仅做校验
     */
    private function _registerpost($request)
    {
        $csminvite = $request->request("csminvite");
        $csminvitesign = $request->request("csminvitesign");
        $csminvcode = $request->request("csminvcode");

        //如果校验码模式，则匹配成 csminvite:notifytype_invkey_userid 的模式进入
        if (!CsmUtils::isNullOrBlank($csminvcode)) {
            $csminvite = "invcode_" . $csminvcode . "_0";
            $csminvitesign = Csminvite::generateSign($csminvite);
        }

        // 由于Hook中获取不到post的csminvite，所以通过session传递参数
        Session::set('csminvite', $csminvite);

        $flag = $this->_checkCsminviteKeyWhileGet($csminvite, $csminvitesign);
        if ($flag === false) {
            return;
        }


        list($invtype, $invkey, $invid) = $this->_parseCsminvitekey($csminvite);
        switch ($invtype) {
            case 'notify':
                $invite = new CsminviteNotify();
                $invite->getAndCheckByInvkey($invkey, $invid);
                break;
            case 'qd':
                $invite = new CsminviteQd();
                $invite->getAndCheckByInvkey($invkey, $invid);
                break;
            case 'invcode':
                $invite = new CsminviteInvcode();
                $invite->getAndCheckByInvkey($invkey, $invid);
                break;
            default:
                $this->_error("参数错误：csminvite#1");
        }
    }

    /**
     * 打开注册页面，校验字段是否被篡改，记录打开时间
     */
    private function _registerget($request)
    {
        $csminvite = $request->request("csminvite");
        $csminvitesign = $request->request("csminvitesign");

        $flag = $this->_checkCsminviteKeyWhileGet($csminvite, $csminvitesign);
        if ($flag === false) {
            return;
        }

        // 路由到对应的注册类型
        list($invtype, $invkey, $invid) = $this->_parseCsminvitekey($csminvite);
        switch ($invtype) {
            case 'notify':
                $invite = new CsminviteNotify();
                $row = $invite->getAndCheckByInvkey($invkey, $invid);
                $invite->visitRegisterUrl($row);
                break;
            case 'qd':
                $invite = new CsminviteQd();
                $row = $invite->getAndCheckByInvkey($invkey, $invid);
                $invite->visitRegisterUrl($row);
                break;
            default:
                $this->_error("参数错误：csminvite#1");
        }
    }

    /**
     * 检查邀请的参数
     * 返回True：邀请链接注册，false：自助注册 or 邀请码注册（因为get方式无法区分是自助注册还是邀请码注册）
     */
    private function _checkCsminviteKeyWhileGet($csminvite, $csminvitesign)
    {

        $config = get_addon_config("csminvite");
        $canregisteroutinvite = $config["canregisteroutinvite"];
        $isspportinvcode = $config["isspportinvcode"];
        if (CsmUtils::isNullOrBlank($csminvite)) {
            // 不允许外部注册&不允许邀请码，则报错
            if ($canregisteroutinvite == "N" && $isspportinvcode == "N") {
                $this->_error($config["outinviteregistermsg"]);
                trace('------------------------');
            } else {
                return false;
            }
        }
        // 校验戳检查

        $csminvitesigncheck = Csminvite::generateSign($csminvite);
        trace("csminvitesign={$csminvitesign}");
        trace("csminvitesigncheck={$csminvitesigncheck}");
        if ($csminvitesigncheck != $csminvitesign) {
            $this->_error("参数错误：csminvitesign");
        }
        return true;
    }

    public static function generateSign($csminvite)
    {

        $config = get_addon_config("csminvite");
        $csminvitemi = $config["csminvitemi"];
        $sign = md5($csminvite . '#' . $csminvitemi);
        trace("generate csminvite=" . $csminvite . '/' . $sign);
        return $sign;
    }

    /**
     * Copy from traits\controller\Jump.php#error function
     */
    private function _error($msg = '', $url = null, $data = '', $wait = 3, array $header = [])
    {
        CsminviteNotifyType::error($msg, $data, $url, $wait, $header);
    }

    private function _parseCsminvitekey($csminvite)
    {
        return explode("_", $csminvite . "_x_x_x");
    }


    /**
     * v1.0.2
     */
    public function configInit(&$params)
    {
        $config = $this->getConfig();
        $params['csminvite'] = ['isspportinvcode' => $config['isspportinvcode'],'canregisteroutinvite' => $config['canregisteroutinvite']];
    }
}
